package br.brpv.silvestrin.conferencia.helper;

import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

import org.apache.commons.codec.binary.Base64;

public class Encryption {

	private static String sharedkey = "&%#@?,:*";

	private static byte[] sharedvector = { 0x12, 0x34, 0x56, 0x78, (byte) 0x90,
			(byte) 0xAB, (byte) 0xCD, (byte) 0xEF };


	public static String encrypt(String plaintext) throws Exception {
		KeySpec ks = new DESKeySpec(sharedkey.getBytes("UTF-8"));
		SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(ks);

		Cipher c = Cipher.getInstance("DES/CBC/PKCS5Padding");
		c.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(sharedvector));
		byte[] encrypted = c.doFinal(plaintext.getBytes("UTF-8"));
		return new String(Base64.encodeBase64(encrypted), "UTF-8");
	}

	public static String decrypt(String ciphertext) throws Exception {
		KeySpec ks = new DESKeySpec(sharedkey.getBytes("UTF-8"));
		SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(ks);

		Cipher c = Cipher.getInstance("DES/CBC/PKCS5Padding");
		c.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(sharedvector));
		byte[] decrypted = c.doFinal(Base64.decodeBase64(ciphertext));
		return new String(decrypted, "UTF-8");
	}
	
}